//npm run create vueComponent/VectorComponent.vue或者npm run create VectorComponent.vue
// 文件路径固定为 "src/components/pages/"
const fs = require("fs");
const path = require("path");
const vuePages = require("./data/pages.json");
const ignores = require("./data/ignores.json");
const form = require("./autopage/form.js");
const table = require("./autopage/table.js");
const blank = require("./autopage/blank.js");
const vuet = require("./autopage/vuet.js");

/**
 * 文件生成器
 */
class Create {
	constructor() {
		const dir = "src/pages/vues/";
		vuePages.forEach(page => {
			const fileName = page.fileName;
			const folderName = fileName.charAt(0).toLowerCase() + fileName.slice(1);//文件夹名首字母小写
			const fileSourcePath = dir + page.folder + folderName;//生成文件路径
			this.generateFile(fileSourcePath, page, fileName);
		});
	}

	/**
	 * 生成文件
	 * @param {*} fileSourcePath 文件夹路径
	 * @param page
	 * @param fileName
	 */
	generateFile(fileSourcePath, page, fileName) {
		const operate = page.operate;
		const params = page.params;
		const isUpdate = page.isUpdate;
		const checkFirstUpperCase = this.checkFirstUpperCase(fileName);
		if (fileName.indexOf("-") !== -1) {
			console.log("Error: 组件名 ${fileName} 不应该包含 - 符号");
			return;
		}
		if (!checkFirstUpperCase) {
			fileName = fileName.charAt(0).toUpperCase() + fileName.slice(1);
		}
		// 去除后缀
		const pointIndex = fileName.lastIndexOf(".");
		if (pointIndex !== -1) {
			fileName = fileName.substring(0, pointIndex);
		}
		// 检测目录是否存在,不存在创建
		const folderExist = this.makeFolder(fileSourcePath);
		if (folderExist && !isUpdate) {
			return;
		}
		const componentName = `${fileSourcePath}/${fileName}.vue`;
		const createResult = this.createTemplate(operate, fileSourcePath, fileName, params);
		if (createResult && createResult.success) {
			console.log("Success 成功创建组件: ", componentName.replace(/\//g, "\\"));
			const newFolderPath = fileSourcePath.replace("vues", "views");
			const moveResult = this.moveFiles(fileSourcePath, newFolderPath, isUpdate, fileName);
			if (moveResult && moveResult.success) {
				console.log("Success 成功移动组件到新目录: ", newFolderPath.replace(/\//g, "\\"));
				// this.updateIgnoreFiles(page);
			}
		}
	}

	updateIgnoreFiles(page) {
		if (ignores.indexOf(page.id.toString()) === -1) {
			ignores.push(page.id.toString());
			const ignoresFilePath = path.resolve(process.cwd()) + "/dev/data/ignores.json";
			fs.writeFileSync(ignoresFilePath, JSON.stringify(ignores));
		}
	}

	/**
	 * 生成对应的文件夹目录
	 */
	makeFolder(fileSourcePath) {
		// 检测目录是否存在,不存在创建
		const minorExist = this.checkFolderOrFileExist(fileSourcePath);
		const minorPath = path.resolve(process.cwd(), fileSourcePath);
		if (minorExist && fs.readdirSync(minorPath).length > 0) {
			return true;
		} else {
			const folderName = fileSourcePath.substring(fileSourcePath.lastIndexOf("/"), fileSourcePath.length);
			const mainPath = path.resolve(process.cwd(), fileSourcePath.replace(folderName, ""));
			const mainExist = this.checkFolderOrFileExist(fileSourcePath.replace(folderName, ""));
			if (mainExist && fs.readdirSync(mainPath).length > 0 && !minorExist) {
				fs.mkdirSync(mainPath + folderName);
			} else if (!mainExist) {
				fs.mkdirSync(mainPath);
				fs.mkdirSync(mainPath + folderName);
			}
			return false;
		}
	}

	/**
	 * 生成文件后将分离文件放到views文件夹下
	 */
	moveFiles(oldFolderPath, newFolderPath, isUpdate, fileName) {
		let result;
		if (!isUpdate) {
			this.makeFolder(newFolderPath);
		}
		try {
			// 样式
			const vueCssPath = `${oldFolderPath}/${fileName}.vue.css`;
			const newCssPath = `${newFolderPath}/${fileName}.vue.css`;
			fs.renameSync(vueCssPath, newCssPath);
			// JS逻辑
			const vueJSPath = `${oldFolderPath}/${fileName}.vue.js`;
			const newJSPath = `${newFolderPath}/${fileName}.vue.js`;
			fs.renameSync(vueJSPath, newJSPath);
			// HTML模板
			const vueHtmlPath = `${oldFolderPath}/${fileName}.vue.html`;
			const newHtmlPath = `${newFolderPath}/${fileName}.vue.html`;
			fs.renameSync(vueHtmlPath, newHtmlPath);
			// 主入口文件
			const vuePath = `${oldFolderPath}/${fileName}.vue`;
			const relativePath = newFolderPath.split("src")[1].substring(1).replace(/\\/g, "/");
			const vueContent = vuet.update(relativePath, fileName);
			fs.writeFileSync(vuePath, vueContent);
			result = {success: true};
		} catch (error) {
			result = {success: false, error};
		}
		return result;
	}

	/**
	 * 检测目录是否存在,不存在创建
	 * @param {*} fileSourcePath 目录路径
	 */
	checkFolderOrFileExist(fileSourcePath) {
		const pathStr = path.resolve(process.cwd(), fileSourcePath);
		try {// file exists
			if (fs.existsSync(pathStr)) {
				return true;
			}
		} catch (err) {// console.error(err)
			return false;
		}
		return false;
	}

	/**
	 * 创建模板
	 * @param operate
	 * @param {*} fileSourcePath 路径名
	 * @param {*} fileName 文件名
	 * @param params
	 */
	createTemplate(operate, fileSourcePath, fileName, params) {
		let result;
		try {
			// 主入口文件
			const vuePath = `${fileSourcePath}/${fileName}.vue`;
			const vueContent = vuet.create(fileName);
			fs.writeFileSync(vuePath, vueContent);
			// 样式
			const vueCssPath = `${fileSourcePath}/${fileName}.vue.css`;
			const vueCssContent = vuet.style();
			fs.writeFileSync(vueCssPath, vueCssContent);
			// JS逻辑
			const fileCommentName = this.getFileComponentName(fileName);
			const vueJSPath = `${fileSourcePath}/${fileName}.vue.js`;
			const vueJSContent = this.getTemplate(operate).javascript(fileCommentName, params);
			fs.writeFileSync(vueJSPath, vueJSContent);
			// HTML模板
			const vueHtmlPath = `${fileSourcePath}/${fileName}.vue.html`;
			const vueHtmlContent = this.getTemplate(operate).html(fileCommentName);
			fs.writeFileSync(vueHtmlPath, vueHtmlContent);
			result = {success: true};
		} catch (error) {
			result = {success: false, error};
		}
		return result;
	}

	/**
	 * 获取组件名
	 * @param {*} compentName 组件名
	 */
	getFileComponentName(compentName) {
		const compentNameList = compentName.split("");
		let compentGenerateName = "";
		for (let i = 0; i < compentNameList.length; i++) {
			let wordsItem = compentNameList[i];
			if (i !== 0) {
				if (this.checkUpperCase(wordsItem)) {
					wordsItem = `-${wordsItem.toLowerCase()}`;
				}
			} else {
				wordsItem = wordsItem.toLowerCase();
			}
			compentGenerateName += wordsItem;
		}
		return compentGenerateName;
	}

	/**
	 * 检测组件名是否首字母大写
	 * @param {*} compentName 文件名
	 */
	checkFirstUpperCase(compentName) {
		const checkItem = compentName.charAt(0) || "";
		return this.checkUpperCase(checkItem);
	}

	/**
	 * 大小写
	 * @param {*} checkItem 比较字符
	 */
	checkUpperCase(checkItem) {
		return /^[A-Z]+$/.test(checkItem);
	}

	getTemplate(operate) {
		let template;
		if (operate === "table") {
			template = table;
		} else if (operate === "form") {
			template = form;
		} else {
			template = blank;
		}
		return template;
	}
}

module.exports = Create;
